<template>
    <div class="menus-box" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)">
        <div class="tabs">
            <el-tabs :tab-position="tabPosition" style="height: 200px;" @tab-click="tabClick">
                <el-tab-pane :label="item.appName" v-for="(item,index) in leftMenuList" :key="item.id"></el-tab-pane>
            </el-tabs>
        </div>
        <div class="mod-meun" v-if="appId=='lhzd'">
            <el-row>
                <el-col :span="16">
                    <h2 class="app-title">功能池分类</h2>
                    <selectTree :tree-data="treeData" @selectTreeDatas="selectDataValue" :flat-tree="flatTree">
                    </selectTree>
                </el-col>
                <el-col :span="8">
                    <el-table border :data="domainResourcesList" element-loading-text="拼命加载中"
                        v-loading="dataListLoading" style="width: 100%;">
                        <el-table-column label="作用域" align="center" prop="name"></el-table-column>
                    </el-table>
                </el-col>
            </el-row>

            <div class="footer">
                <el-button @click="$router.go(-1)">返回上一页</el-button>
                <el-button type="primary" @click="addSubmit('ruleForm')">保存</el-button>
            </div>
        </div>
    </div>
</template>
<script>
    import API from '@/api';
    import webSourceData from './web.json';
    export default {
        data() {
            return {
                tabPosition: 'left',
                dataForm: {},
                dataList: [],
                dataListLoading: false,
                loading: false,
                addOrUpdateVisible: false,
                leftMenuList: [],
                appId: '',
                roleId: '',
                domainResourcesList: [],
                selectData: [],
                defaultProps: {
                    children: 'pageChildren',
                    label: 'name'
                },
                treeData: [],
                flatTree: [],
                pageResources:[]
            };
        },

        created: function () {
            console.log(webSourceData.data.webResources);
            //this.treeData = this.compileTreeData(webSourceData.data.webResources);
            console.log(this.treeData);
        },
        mounted() {
            this.roleId = this.$route.query.roleId;
            this.appId = this.$route.query.appId;
            this.getLeftMenus();
        },
        methods: {
            renderContent(h, {
                node,
                data,
                store
            }) {
                return (<span class = "custom-tree-node-app" ><span on-click = {() => this.showBtnScope(data)} > {store} </span> </span>
                );
            },
            getLeftMenus() {
                var params = {
                    pageNum: 1,
                    pageSize: 1000
                };
                this.loading = true
                API.systemManger.systemList(params).then(res => {
                    this.loading = false
                    this.leftMenuList = res.data.rows;
                    this.appId = res.data.rows[0].appId;
                    this.getList();
                });
            },

            tabClick(tab, event) {
                this.appId = this.leftMenuList[tab.index]['appId'];
            },
            // 显示作用域
            selectDataValue(val) {
                if (val.domainResources) {
                    this.domainResourcesList = val.domainResources;
                } else {
                    this.domainResourcesList = [];
                }
            },
            treeDealEach(tress) {
                var pageResources = []
                function eachDeal (data) {
                    for (var j in data) {
                        if (data[j].roleSelect && data[j].type != 'button'){
                        pageResources.push({
                                functionResources: [],
                                pageId: data[j].id
                            });
                            var child = data[j].children;
                              if (child && child.length > 0) {
                                    eachDeal(child)
                                }
                }
                if (data[j].roleSelect && data[j].type == 'button'){
                    pageResources[j]['functionResources'].push({
                                        functionId: data[j].id,
                                        domainResources:[]
                                    });
                                        var child2 = data[j].domainResources;
                                        if (child2 && child2.length > 0) {
                                            if (pageResources[j].functionResources.length>0) {
                                                for (var k in child2) {
                                                    pageResources[j].functionResources[0]['domainResources'].push({
                                                        domainId: child2[k].id
                                                    });
                                                }
                                            }

                                        }
                                    
                        }

                    }
                 
                }
                eachDeal(tress)
                return pageResources
            },
            // 保存
            addSubmit() {
                var tress = this.treeData;
                if (this.treeDealEach(tress).length > 0) {

                    var data = {
                        pageResources: this.treeDealEach(tress),
                        roleId: this.roleId,
                        appId: this.appId
                    };
                    API.role.saveAppPowerRole(data).then(res => {
                        if (res.code == '20000000') {
                            this.$message({
                                type: 'success',
                                message: '保存成功'
                            });
                        } else {
                            this.$message.error(res.message);
                        }
                    });
                } else {
                    this.$message.error('请先勾选');
                }
            },
            // 获取列表数据
            getList() {
                this.dataListLoading = true;
                var data = {
                    appId: this.appId,
                    roleId: this.roleId
                };
                this.loading = true
                API.role.appPowerRoleList(data).then(res => {
                    this.loading = false
                    this.dataListLoading = false;
                    this.dataList = res.data.webResources;
                    this.treeData = this.compileTreeData(res.data.webResources);
                });
            },
            filterSelect(selection) {
                console.log(selection);
                this.selectData = selection;
                let arr = []; // 循环children取值
                function filterData(val) {
                    arr.push(val);
                    if (val.children) {
                        val.children.map(item => {
                            filterData(item);
                        });
                    }
                } // 源数据中取出选中的数据
                console.log(this.dataList.children);
                this.dataList.map(item => {
                    item.children.map(item2 => {
                        selection.map(val => {
                            // if (val.id === item2.id) {
                            filterData(val);
                            // }
                        });
                    });
                });

                return arr;
            },
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        // toggleRowSelection有两个参数，第一个是每个选中数据，第二个是点击勾选的这行是否选中，树形结构需要，不然子集选中，本身不给选中
                        this.$refs.multipleTable.toggleRowSelection(row, true);
                    });
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            handleSelectionChange(selection, val) {
                var userData = [];
                if (Object.keys(val).length == 3) {
                    userData = val.children;
                } else {
                    userData = val;
                }
                if (val.length == 0) {
                    this.$refs.multipleTable.clearSelection();
                } else {
                    // this.$refs.multipleTable.toggleRowSelection(val, true);
                    this.selectData = userData;
                }
            },

            //数据初始化(添加某些必要属性)
            compileTreeData(arr) {
                var nodes = [];

                function Vnode(config) {
                    var _vnode = {
                        id: config.id,
                        level: config.level,
                        type: config.type,
                        name: config.name,
                        appId: config.appId,
                        pageId: config.pageId,
                        parent: null,
                        next: null,
                        prev: null,
                        children: [],
                        domainResources: config.domainResources,
                        expanded: false,
                        expand: function () {
                            this.expanded = !this.expanded;
                        },
                        checkStatus: function (type) {
                            type = type || 0;
                            if (this.roleSelect) {
                                return true;
                            } else {
                                var rc = false;
                                if ((type == -1 || type == 0) && this.prev) {
                                    rc = this.prev.checkStatus(-1);
                                }
                                if ((type == -1 || type == 0) && this.next) {
                                    rc = this.next.checkStatus(1);
                                }
                                return rc;
                            }
                        },
                        roleSelect: config.roleSelect,
                        check: function (bool, unChild) {
                            this.roleSelect = bool == undefined ? !this.roleSelect : bool;
                            //if(this.checked) this.expanded = true;
                            if (this.parent) {
                                if (!this.parent.checked) {
                                    if (this.roleSelect) this.parent.check(true, true);
                                } else if (!this.checkStatus()) {
                                    if (this.level == 0) console.log(this.roleSelect);
                                    if (this.parent.roleSelect && !this.roleSelect) this.parent.check(false,
                                        true);
                                }
                            }
                            if (unChild) return false;
                            if (this.children.length) {
                                for (var i = 0; i < this.children.length; i++) {
                                    this.children[i].check(this.roleSelect);

                                }
                            }
                        },
                        selected: false,
                        select: function (item) {},
                        append: function (node) {
                            node.parent = this;
                            var prev = this.children[this.children.length - 1];
                            if (prev) {
                                prev.next = node;
                                node.prev = prev;
                            }
                            this.children.push(node);
                        }
                    };
                    if (config.pageChildren && config.pageChildren.length) {
                        for (var i = 0; i < config.pageChildren.length; i++) {
                            config.pageChildren[i].type = 'page';
                            config.pageChildren[i].level = config.level + 1;
                            _vnode.append(Vnode(config.pageChildren[i]));
                        }
                    }
                    if (config.children && config.children.length) {
                        for (var i = 0; i < config.children.length; i++) {
                            config.children[i].type = 'button';
                            config.children[i].level = config.level + 1;
                            _vnode.append(Vnode(config.children[i]));
                        }
                    }
                    return _vnode;
                }
                arr.forEach(item => {
                    item.level = 0;
                    nodes.push(Vnode(item));
                });

                console.log(arr);
                return nodes;
            },
       
        }
    };
</script>
<style scoped>
    .menus-box {
        background: #fff;
        padding: 20px;
        min-height: 100%;
    }

    .menus-box .tabs {
        float: left;
        width: 15%;
    }

    .menus-box .mod-meun {
        float: right;
        width: 83%;
    }

    .footer {
        text-align: center;
        margin-top: 30px;
        margin-bottom: 100px;
    }

    .app-title {
        color: #909399;
        margin-bottom: 20px;
        font-size: 12px;
        background: rgba(235, 238, 245, 0.6);
        height: 38px;
        line-height: 38px;
        padding-left: 10px;
        padding-right: 10px;
    }
</style>